<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.timesheet_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.timesheet_delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.timesheet_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.timesheet_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.timesheet_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog class="dialog" ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" @close="closeDialog">
      <avue-form v-if="showDialog" :defaults.sync="defaults" ref="form" v-model="form" :option="dialogOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="submit"><i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button v-if="dialogTitle !== '详情'" size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/product/timesheet';
import { getList as getProductionlineList } from '@/api/product/productionline';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'TIME_SHEET',
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        columnBtn: false,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchSpan: 4,
        column: [
          {
            label: '报工单号',
            prop: 'timesheetNo'
          },
          {
            label: '产线',
            prop: 'lineName',
            search: true,
            type: 'select',
            allowCreate: true,
            filterable: true,
            props: {
              label: 'name',
              value: 'id'
            },
            dicData: []
          },
          {
            label: '班组',
            prop: 'shiftGroupName'
          },
          {
            label: '报工日期',
            prop: 'timesheetDate'
          },
          {
            label: '完工数量',
            prop: 'quantityFinished'
          },
          {
            label: '不良数量',
            prop: 'ngQuantity'
          },
          {
            label: '实出勤人数',
            prop: 'actualAttend'
          },
          {
            label: '提交人',
            prop: 'submitter'
          },
          {
            label: '最后修改日期',
            prop: 'updateTime'
          }
        ]
      },
      data: [],
      modalName: '', //打开的模态框名称
      showDialog: false,
      dialogTitle: '新增',
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '125',
        column: [
          {
            label: '车间',
            prop: 'workshopId',
            type: 'select',
            dicUrl: '/api/mes-admin/workshop/key-value',
            props: {
              label: 'workshopName',
              value: 'workshopId'
            },
            rules: [
              {
                required: true,
                message: '请选择车间',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产线',
            prop: 'lineId',
            type: 'select',
            props: {
              label: 'name',
              value: 'id'
            },
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择产线',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '报工日期',
            prop: 'timesheetDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            rules: [
              {
                required: true,
                message: '请选择报工日期',
                trigger: 'blur'
              }
            ],
            pickerOptions: {
              disabledDate: (time) => {
                return time.getTime() > new Date().getTime();
              }
            }
          },
          {
            label: '出勤工时(小时)',
            prop: 'manHours',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请选择出勤工时',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '完工数量',
            prop: 'quantityFinished',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请选择完工数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良数量',
            prop: 'ngQuantity',
            type: 'number',
            precision: 0,
            minRows: 0,
            rules: [
              {
                required: true,
                message: '请选择不良数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '应出勤人数',
            prop: 'expectAttend',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请选择应出勤人数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '实际出勤人数',
            prop: 'actualAttend',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请选择实际出勤人数',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(),
      defaults: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.timesheet_add, false),
        viewBtn: this.vaildData(this.permission.timesheet_view, false),
        delBtn: this.vaildData(this.permission.timesheet_delete, false),
        editBtn: this.vaildData(this.permission.timesheet_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  watch: {
    'form.workshopId'(val) {
      getProductionlineList(1, 10000, { workshopId: val })
        .then((res) => {
          this.dialogOption.column[1].dicData = this._get(res, 'data.data.records', []);
          let lineIdIndex = this._findIndex(this.dialogOption.column[1].dicData, { id: this.form.lineId });
          if (lineIdIndex === -1) {
            this.form.lineId = '';
          }
        })
        .catch((err) => {
          this.dialogOption.column[1].dicData = [];
        });
    }
  },
  mounted() {
    getProductionlineList(1, 10000)
      .then((res) => {
        this.option.column[1].dicData = this._get(res, 'data.data.records', []);
      })
      .catch((err) => {
        this.dialogOption.column[1].dicData = [];
      });
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.form.allDisabled = true;
      });
      // this.$refs.form.allDisabled = true;
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        //将值为null的字段值转为undefined，防止被数字类型的输入框将null转为1
        Object.keys(this.form).forEach((item) => {
          const key = this.form[item];
          if (key === null) {
            this.form[item] = undefined;
          }
        });
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.lineName) {
        params.lineId = params.lineName;
        delete params.lineName;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 打开新增模态框
     */
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.form.workshopId = '';
    },
    /**
     * 关闭模态框清空表单
     */
    closeDialog() {
      this.$refs.form.resetFields();
      this.form = {};
    },
    /**
     * 添加报工单
     */
    submit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          if (this.dialogTitle === '新增') {
            add(this.form).then(
              (res) => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: res.data.msg
                });
                this.showDialog = false;
                done();
              },
              (error) => {
                done();
              }
            );
          } else if (this.dialogTitle === '编辑') {
            update(this.form).then(
              (res) => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: res.data.msg
                });
                this.showDialog = false;
                done();
              },
              (error) => {
                done();
              }
            );
          }
        }
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog ::v-deep .avue-form__menu {
  display: none;
}
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
</style>
